﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

namespace eWallet.Serialization
{
	public static class BinarySerializer
	{

		/// <summary>
		/// Deserializes the given byte array to an object of the given type.
		/// </summary>
		/// <typeparam name="T">The type of the object to deserialize to.</typeparam>
		/// <param name="data">The byte array to deserialize.</param>
		public static T Deserialize<T>(byte[] data)
		{
			using (MemoryStream strm = new MemoryStream())
			{
				using (BinaryWriter writer = new BinaryWriter(strm))
				{
					writer.Write(data);
					writer.Flush();

					strm.Position = 0;
					BinaryFormatter formatter = new BinaryFormatter();
					object target = formatter.Deserialize(strm);

					return (T)target;
				}
			}
		}

		/// <summary>
		/// Serializes the given object to a byte array.
		/// </summary>
		/// <param name="source">The object to serialize.</param>
		public static byte[] Serialize(object source)
		{
			using (MemoryStream strm = new MemoryStream())
			{
				BinaryFormatter formatter = new BinaryFormatter();
				formatter.Serialize(strm, source);
				
				strm.Position = 0;
				using (BinaryReader reader = new BinaryReader(strm))
				{
					byte[] data = new byte[strm.Length];
					reader.Read(data, 0, data.Length);

					return data;
				}
			}
		}

	}
}
